<?php
/**
 * 大赛报名
 */
namespace Beerus\Modules\DesignerCompetition2022\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DesignerCompetition2022\Actions\EditInfo;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerCompetition\DesignerAwardSign2020;
use Doraemon\model\DesignerCompetition2021\DcUserInfo;
use Doraemon\model\DesignerCompetition2021\DcUserInfoAdmin;
use Doraemon\model\DesignerCompetition2021\DcUserSignAdmin;
use Doraemon\model\Member;
use Doraemon\model\ReDesignerCompetition\Sign\DcUserInfoHelper;
use Doraemon\model\ReDesignerCompetition\Sign\DcUserSignHelper;
use Doraemon\pockets\constInterface\Designer\DesignerCompetition2022;
use Doraemon\pockets\datebase\MedooScrew;
use Doraemon\service\admin\EnterAward;
use Doraemon\service\BusinessUser\EncryptPhone;
use Doraemon\service\DesignerCompetition2021\SignUp;
use Doraemon\service\DesignerCompetition2021\DcAdmin;
use Doraemon\tools\Area;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use hhz\constant\basic\UserExtendPhoneScene;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Medoo\Medoo;
use Beerus\Modules\DesignerCompetition\Actions\EditHonor;

class InfoController extends Controller implements DesignerCompetition2022 {
    const PAGE_SIZE = 15;

    /**
     * 大赛报名列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content) {
        $requestParams = $request->all();
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $condition = $this->condition($requestParams);

        $tab = new Tab();
        $tab->addLink('报名作品列表', '/admin/DesignerCompetition2022/sign');
        $tab->addLink('报名信息列表', '/admin/DesignerCompetition2022/info', true);
        return $content
            ->header('大赛报名列表')
            ->body($tab)
            ->row(self::indexGrid($condition, $page, $pageSize));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition, $page, $pageSize) {
        $total = (DcUserSignHelper::getInstance(self::SIGN_YEAR))->getSignCntByCondition($condition);
        $list = (DcUserInfoHelper::getInstance(self::SIGN_YEAR))->getInfoListByCondition($condition, $page, $pageSize);
        if (!empty($list)) {
            self::formatUserInfoList($list);
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('designer_type', '参赛身份')->select(DcAdmin::DESIGNER_TYPE_TXT);
                        $filter->equal('competition_area', '赛区')->select(DcAdmin::COMPETITION_AREA_NAME);
                        $filter->equal('uid', '用户uid');
                        $filter->equal('data_status', '数据状态')->select([
                            1 => '已报名',
                            2 => '待修改',
                            3 => '已修改'
                        ]);
                    });

                    $filter->expand();
                });

                $grid->column('id', '信息id')->width(100);
                $grid->column('uid', '用户uid')->width(100);
                $grid->column('nick', '用户昵称')->width(100);
                $grid->column('designer_type', '参赛身份')->width(100);
                $grid->column('competition_area', '参赛地区')->width(100);
                $grid->column('competition_name', '个人/机构名称')->width(120);
                $grid->column('intro', '个人/机构介绍')->width(200);
                $grid->column('phone', '电话')->width(100);
                $grid->column('city', '城市')->width(100);
                $grid->column('address', '地址')->width(200);
                $grid->column('photo', '个人/机构图片')->width(140)->display(function () {
                    return '<a href="' . $this->photo . '" target="_blank">
                                <img width="100px" height="100px" src="' .$this->photo . '">
                            </a>';

                });
                $grid->column('organ_logo', '机构logo')->width(140)->display(function () {
                    if ($this->organ_logo) {
                        return '<a href="' . $this->organ_logo . '" target="_blank">
                                <img width="100px" height="100px" src="' .$this->organ_logo . '">
                            </a>';
                    }
                });
                $grid->column('recommend_organ', '推荐机构')->width(150);

                $grid->setActionClass(DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->add(new EditInfo());
                });
            }
        );

        return $gridList;
    }

    private function condition($request) {
        $response = [];
        if (!empty($request['uid'])) {
            $response['uid'] = $request['uid'];
        }
        if (!empty($request['designer_type'])) {
            $response['designer_type'] = $request['designer_type'];
        }
        if (!empty($request['competition_area'])) {
            $response['competition_area'] = $request['competition_area'];
        }
        if (!empty($request['data_status'])) {
            $response['data_status'] = $request['data_status'];
        }
        return $response;
    }

    public function edit(Request $request, Content $content, $id = 0) {
        $data = DcUserInfoAdmin::get('*', ['id' => $id]);
        list($data['province'], $data['city']) = explode(',', $data['city']);
        $data['photo_url'] = ImgUrl::getUrl(
            ImgUrl::APPTYPE_BAUTH,
            $data['photo'],
            ImgUrl::IMAGE_SIZE_SQ_THUMB);
        // 机构logo
        $data['organ_logo_url'] = !empty($data['organ_logo']) ? ImgUrl::getUrl(
            ImgUrl::APPTYPE_BAUTH,
            $data['organ_logo'],
            ImgUrl::IMAGE_SIZE_SQ_THUMB
        ) : '';
        $form = new Form($data);
        $form->text('id', 'ID')->readOnly();

        $competitionNameLabel = '个人名称';
        $introLabel = '个人简介';
        $photoLabel = '个人照片';
        if ($data['designer_type'] == DcAdmin::DESIGNER_TYPE['organization']) {
            $competitionNameLabel = '机构名称';
            $introLabel = '机构简介';
            $photoLabel = '机构照片';
        }
        $form->text('competition_name', $competitionNameLabel)->required();
        $form->textarea('intro', $introLabel)->required();
        $form->text('phone', '电话')->required();
        $allCity = $data['province'] > 0 ? Area::getLocation($data['province']) : [];
        $form->select('province', '请选择省份')
            ->options(Area::getLocation())
            ->load('city', '/admin/BasicSetting/area_list')
            ->default($data['province'])
            ->required();
        $form->select('city', '请选择市、区')
            ->options($allCity)
            ->default($data['city'])
            ->required();
        $form->text('address', '地址')->required();
        $form->imgUpload('photo', $photoLabel, false,
            [
                'imgType' => ImgUrl::APPTYPE_BAUTH,
                'imgSize' => ImgUrl::IMAGE_SIZE_SQ_THUMB
            ])
            ->required();
        if ($data['designer_type'] == DcAdmin::DESIGNER_TYPE['organization']) {
            $form->imgUpload('organ_logo', '机构logo', false,
                [
                    'imgType' => ImgUrl::APPTYPE_BAUTH,
                    'imgSize' => ImgUrl::IMAGE_SIZE_SQ_THUMB
                ]);
        }
        $form->select('recommend_organ', '推荐机构')->options(DcAdmin::RECOMMEND_ORGAN_LIST);
        $form->confirm('确定提交吗？');
        $form->action('/admin/DesignerCompetition2021/info/save');

        $header = '信息修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => '报名信息列表'],
                ['text' => '编辑报名信息'],
            )->row($tab);
    }

    public function save(Request $request) {
        $request = $request->all();
        $city = $request['province'] . ',' . $request['city'];
        $data = [
            'competition_name' => $request['competition_name'],
            'intro' => $request['intro'],
            'phone' => $request['phone'],
            'address' => $request['address'],
            'photo' => $request['photo'],
            'organ_logo' => $request['organ_logo'],
            'recommend_organ' => $request['recommend_organ'],
            'city' => $city,
            'competition_area' => DcAdmin::getCompetitionArea($city)
        ];

        $dcOldUserInfo = DcUserInfoAdmin::get('*', ['id' => $request['id']]);
        // 如果是未认证设计师则修改designer_auth的phone
        $designerAuthInfo = DesignerAuth::getInfoByUid($request['uid']);
        //处理手机号加密业务
        $encryptPostPhone = EncryptPhone::createEncryptPhone($data['phone']);
        $authEncryptId = EncryptPhone::getEncryptPhoneId($data['phone'],UserExtendPhoneScene::DESIGNER_AUTH_PHONE);
        if ($designerAuthInfo['identity_info_audit_status'] == DesignerAuth::STATUS_AUDIT_SUPPLEMENT && $designerAuthInfo['encrypt_phone'] != $encryptPostPhone) {
            DesignerAuth::update(
                //['phone' => $data['phone']],
                ['uid' => $dcOldUserInfo['uid'],
                    ['encrypt_phone_id' => $authEncryptId],
                    ['encrypt_phone' => $encryptPostPhone],
                ]);
        }
        $rs = DcUserInfoAdmin::updateInfo($data, ['id' => $request['id']]);
        if ($rs === false) {
            $error = new MessageBag(['title' => '修改失败']);
            return back()->with(compact('error'));
        }
        // 如果个人or机构名称/个人or机构照片有修改，则重新生成海报
        if ($dcOldUserInfo['competition_name'] != $data['competition_name'] || $dcOldUserInfo['photo'] != $data['photo']) {
            DcAdmin::createPoster($dcOldUserInfo['uid'], $data);
        }
        Log::info("后台修改参赛信息", [
            'admin_uid' => Admin::user()->id,
            'old_competition_info' => $dcOldUserInfo,
            'new_competition_info' => $data
        ]);
        $success = new MessageBag(['title' => '修改成功']);
        return redirect('/admin/DesignerCompetition2021/info')->with(compact('success'));
    }

    public static function formatUserInfoList(&$list) {
        $userIds = array_column($list, 'uid');
        $memberInfo = Member::getUsers($userIds);
        foreach ($list as &$item) {
            $item['nick'] = empty($memberInfo[$item['uid']]['nick']) ? '' : $memberInfo[$item['uid']]['nick'];
            $item['designer_type'] = self::DESIGNER_TYPE_TXT[$item['designer_type']];

            // 参赛信息
            $item['competition_area'] = self::COMPETITION_AREA_NAME[$item['competition_area']];
            $competitionInfo = (DcUserInfoHelper::getInstance(self::SIGN_YEAR))->getItemByUid($item['uid']);
            $item['city'] = \Hhz\AdministrativeRegion\Region::getAreaDetailByCode($competitionInfo['city']);
            // 个人/机构照片
            $item['photo'] = ImgUrl::getUrl(
                ImgUrl::APPTYPE_BAUTH,
                $item['photo'],
                ImgUrl::IMAGE_SIZE_SQ_THUMB);
            // 机构logo
            $item['organ_logo'] = !empty($item['organ_logo']) ? ImgUrl::getUrl(
                ImgUrl::APPTYPE_BAUTH,
                $item['organ_logo'],
                ImgUrl::IMAGE_SIZE_SQ_THUMB
            ) : '';
            $item['recommend_organ'] = self::RECOMMEND_ORGAN_LIST[$item['recommend_organ']];
        }
    }

}
